import imp
import os
import glob
import inspect

from autoscrapy.utils import log

LOG = log.get_logging(__name__)


class extensionManager(object):

    def __init__(self, path):
        self._plugins = {}
        self._load_from_path(path)

    def _load_from_path(self, filepath):
        filepath = os.path.dirname(__file__) + '/' + filepath
        files = glob.glob(filepath + '/*.py')

        LOG.info("Loading plugins filepath %s from files %s", filepath, files)
        for _file in files:
            _rfile = os.path.realpath(_file)
            filename = os.path.basename(_file)
            if filename == '__init__.py':
                continue

            mod_name = filename.split('.')[0]
            expected_class = ''.join([_m.title() for _m in mod_name.split('_')])

            # FIXEME, catch fail exception
            py_mod = imp.load_source(mod_name, _file)

            if hasattr(py_mod, expected_class):
               class_inst = getattr(py_mod, expected_class)

               if class_inst.get_type() not in self._plugins:
                   self._plugins[class_inst.get_type()] = class_inst
                   LOG.info("Loading plugin for name %s", class_inst.get_type())
               else:
                   LOG.warn("class %s has exist with class type %s",
                            expected_class, class_inst.get_type())
            else:
                LOG.warn("file %s not exist class %s", _file, expected_class)

